package com.fy.core.kaptcha;

import cn.hutool.core.codec.Base64;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.fy.core.vo.ApiRest;
import com.fy.sys.mapper.UserMapper;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
public class CaptcherController {

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;


    @Autowired
    private UserMapper userMapper;

    @GetMapping("/captchaImage")
    public ApiRest getCode(HttpServletResponse response, HttpSession session) throws IOException
    {

        // 保存验证码信息
        String id = IdWorker.getIdStr();
        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        String captchaType = "math";
        if ("math".equals(captchaType))
        {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1); //答案储存在服务端
            image=captchaProducerMath.createImage(capStr);//题目图片响应给客户端
            //session.setAttribute("code",code);
            // code save to db
            userMapper.saveCode(id,code);

            image = captchaProducerMath.createImage(capStr); //题目图片响应给客户端
        }
        else if ("char".equals(captchaType))
        {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return ApiRest.failure("fail");
        }

        Map data = new HashMap();
        data.put("img",Base64.encode(os.toByteArray()));
        data.put("id",id);

        return ApiRest.success(data);
    }
}
